package cn.edu.szpt.qqdemov3.fragments;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.edu.szpt.qqdemov3.MainActivity;
import cn.edu.szpt.qqdemov3.R;
import cn.edu.szpt.qqdemov3.adapters.QQContactAdapter;
import cn.edu.szpt.qqdemov3.beans.QQContactBean;
import cn.edu.szpt.qqdemov3.dbutils.MyDbHelper;
import cn.edu.szpt.qqdemov3.dialogs.NewContactDialog;
import cn.edu.szpt.qqdemov3.dialogs.OnDialogCompletedListener;

public class QQContactFragment extends Fragment {
    private ExpandableListView exlvContact;
    private QQContactAdapter adapter;
    private List<String> groupdata;
    private Map<String,List<QQContactBean>> childdata;
    private ImageView imgLoginIcon;
    private TextView tv_AddBtn;
    private String photos;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view;
        view = inflater.inflate(R.layout.activity_qqcontact,container,false);
        tv_AddBtn = view.findViewById(R.id.tv_AddBtn);
        tv_AddBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showNewContactDialog();
            }
        });

        exlvContact = view.findViewById(R.id.exlvContact);
        imgLoginIcon = view.findViewById(R.id.imgLoginIcon);

        Bitmap bmp = BitmapFactory.decodeFile(MainActivity.loginedUser.getQq_imgurl());
        imgLoginIcon.setImageBitmap(bmp);

        groupdata = new ArrayList<>();
        childdata = new HashMap<>();
        initialData();

        adapter = new QQContactAdapter(getContext(),groupdata,childdata);

        exlvContact.setAdapter(adapter);
        registerForContextMenu(exlvContact);
        return view;
    }

    @Override
    public void onCreateContextMenu(@NonNull ContextMenu menu, @NonNull View v, @Nullable ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        ExpandableListView.ExpandableListContextMenuInfo info = (ExpandableListView.ExpandableListContextMenuInfo) menuInfo;
        long packedPosition = info.packedPosition;
        //用于判断是组项数据还是子项数据，0表示组项数据，1表示子项数据
        int type = ExpandableListView.getPackedPositionType(packedPosition);
        if(type == ExpandableListView.PACKED_POSITION_TYPE_CHILD)
            getActivity().getMenuInflater().inflate(R.menu.menu_contact,menu);
    }

    @Override
    public boolean onContextItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case R.id.menuitem_newcontact:
                //添加联系人
                showNewContactDialog();
                break;
            case R.id.menuitem_delcontact:
                //删除联系人
                delContact(item);
                break;

        }
        return super.onContextItemSelected(item);
    }

    private void showNewContactDialog(){
        NewContactDialog dialog = new NewContactDialog();
        dialog.setListener(new OnDialogCompletedListener() {
            @Override
            public void onCompleted() {
                initialData();
                adapter.notifyDataSetChanged();
            }
        });
        dialog.show(getChildFragmentManager(),"");
    }

    private void delContact(MenuItem item){
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle(R.string.confirm_dlg_title)
                .setMessage(R.string.confirm_dlg_message)
                .setIcon(R.mipmap.ic_launcher_round)
                .setPositiveButton(R.string.confirm_dlg_btnyes, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //执行删除操作
                        ExpandableListView.ExpandableListContextMenuInfo info = (ExpandableListView.ExpandableListContextMenuInfo) item.getMenuInfo();
                        long packedPosition = info.packedPosition;
                        int group_pos = ExpandableListView.getPackedPositionGroup(packedPosition);
                        int child_pos = ExpandableListView.getPackedPositionChild(packedPosition);
//        Toast.makeText(getContext(),"group_pos=" + group_pos + "\t" + "child_pos=" + child_pos,Toast.LENGTH_LONG).show();
                        MyDbHelper helper = new MyDbHelper(getContext());
                        SQLiteDatabase db = helper.getWritableDatabase();
                        String sql ="delete from QQ_Contact where qq_num=? and belong_qq=? ";
                        List<QQContactBean> list =childdata.get(groupdata.get(group_pos));
                        QQContactBean bean = list.get(child_pos);
                        db.execSQL(sql,new Object[]{bean.getQq_num(),MainActivity.loginedUser.getQq_num()});
                        initialData();
                        adapter.notifyDataSetChanged();
                    }
                })
                .setNegativeButton(R.string.confirm_dlg_btnno,null)
                .show();

    }

    @SuppressLint("Range")
    private void getPhoneContacts(){
        groupdata.add("本机联系人");
        List<QQContactBean> list = new ArrayList<>();

        ContentResolver cr = getContext().getContentResolver();
        Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI,null,null,null,null);
        while (cursor.moveToNext()){
            String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            Uri imguri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI,Long.parseLong(contactId));

            Cursor phoneCursor = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=?",
                    new String[]{contactId},null);
            String phone="";
            while(phoneCursor.moveToNext()){
                phone += phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            }
            if(phone.length()>0){
                phone = phone.substring(0,phone.length()-1);
            }
            Cursor emailCursor = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                    null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=?",
                    new String[]{contactId},null);
            String email="";
            while(emailCursor.moveToNext()){
                email += emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
            }
            if(email.length()>0){
                email = email.substring(0,email.length()-1);
            }


            QQContactBean bean = new QQContactBean(contactId,name,imguri.toString(),
                    phone,email,"本机联系人");
            list.add(bean);
        }

        childdata.put("本机联系人",list);

        saveContact();
    }

    private void saveContact() {
        photos = this.getActivity().getExternalFilesDir("photos").toString();
        
    }

    @SuppressLint("Range")
    private void initialData(){
        groupdata.clear();
        childdata.clear();

        getPhoneContacts();

        MyDbHelper helper = new MyDbHelper(getContext());
        SQLiteDatabase db = helper.getReadableDatabase();
        String sql ="select distinct belong_country from view_Contact where belong_qq=?";

        Cursor groupCursor = db.rawQuery(sql,new String[]{MainActivity.loginedUser.getQq_num()});

        while(groupCursor.moveToNext()){
            String countryname = groupCursor.getString(groupCursor.getColumnIndex("belong_country"));
            groupdata.add(countryname);
            List<QQContactBean> list = new ArrayList<>();
            sql = "select * from view_contact where belong_qq=? and belong_country=?";
            Cursor childCursor = db.rawQuery(sql,new String[]{MainActivity.loginedUser.getQq_num(),countryname});
            while(childCursor.moveToNext()){
                QQContactBean bean = new QQContactBean(childCursor.getString(childCursor.getColumnIndex("qq_num")),
                        childCursor.getString(childCursor.getColumnIndex("qq_name")),
                        childCursor.getString(childCursor.getColumnIndex("qq_imgurl")),
                        childCursor.getString(childCursor.getColumnIndex("qq_online")),
                        childCursor.getString(childCursor.getColumnIndex("qq_action")),
                        childCursor.getString(childCursor.getColumnIndex("belong_country")));
                list.add(bean);
            }
            childdata.put(countryname,list);
        }
    }

}
